var express = require("express");
var router = express.Router();
const lowdb = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const shortid = require("shortid");
const adapter = new FileSync(__dirname + "/" + "../data/db.json");
const moment = require("moment");
const accountModel = require("../models/accountsModel");
const { default: mongoose } = require("mongoose");

/* // 测试
console.log(moment("2024-04-09").toDate()); */

/* // 获取 db 对象
const db = lowdb(adapter); */

// 初始化数据
/* db.defaults({
  accounts: [],
}).write(); */

// 记账本列表
router.get("/account", function (req, res, next) {
  /* let accounts = db.get("accounts").value();
  console.log(accounts); */
  accountModel
    .find()
    .sort({
      time: -1,
    })
    .exec((err, data) => {
      if (err) {
        res.status(500).send("读取错误");
        return;
      }
      console.log(moment(data.time).format("YYYY-MM-DD"));
      res.render("list", {
        accounts: data,
        moment: moment,
      });
    });
});

// 添加记录
router.get("/account/create", (req, res, next) => {
  res.render("create");
});

router.post("/account", (req, res) => {
  console.log(req.body);
  accountModel.create(
    {
      ...req.body,
      time: moment(req.body.time).toDate(),
    },
    (err, data) => {
      if (err) {
        // console.log(err);
        res.status(500).send("插入失败");
        return;
      }
      console.log(data);
      msg = "添加成功";
      url = "/account";
      res.render("success", {
        msg: msg,
        url: url,
      });
    },
  );
  /* // 生成 id
  let id = shortid.generate();
  db.get("accounts")
    // .push({
    .unshift({
      id: id,
      ...req.body,
    })
    .write();
  // res.send("添加记录"); */
});

// 删除记录
router.get("/account/:id", (req, res) => {
  // 获取 id
  let id = req.params.id;
  /* db.get("accounts")
    .remove({
      id: id,
    })
    .write(); */
  accountModel.deleteOne(
    {
      _id: id,
    },
    (err, data) => {
      if (err) {
        res.statusCode(500).send("删除失败~~");
        return;
      }
      // 提醒
      // res.send("删除成功");
      msg = "删除成功";
      url = "/account";
      res.render("success", {
        msg: msg,
        url: url,
      });
    },
  );
});

module.exports = router;
